<?php

namespace common\service;

use common\exception\LogicException;
use common\model\MediaModel;
use support\ErrorCode;
use think\Cache;

class MediaService
{

    /**
     * 获取媒体缩略图
     * @param $mediaData
     * @param $mediaServer
     * @return array
     */
    protected function getMediaThumb($mediaData, $mediaServer)
    {
        // 生成 media data
        $uploadType = $mediaData['upload_type'] ?? 'media_service';
        $thumbUrl = '';
        $path = $mediaData['path'] ?? '';
        $md5Name = $mediaData['md5_name'] ?? '';
        $ext = $mediaData['ext'] ?? '';
        $width = $mediaData["width"] ?? '';
        $height = $mediaData["height"] ?? '';
        $mediaSize = $mediaData["size"] ?? '';
        $thumb = $mediaData['thumb'];
        switch ($mediaData["type"]) {
            case 'video':
                // 视频保存原始尺寸
                $mediaSize = "{$width}x{$height}";
                if ($uploadType === 'media_service') {
                    $thumbUrl = "{$mediaServer['request_url']}/{$path}{$md5Name}.jpg";
                } else {
                    $thumbUrl = $thumb;
                }
                break;
            case 'image':
                if ($uploadType === 'media_service') {
                    // 获取图片上传尺寸
                    $sizeArray = explode(',', $mediaSize);
                    $minSize = 999999;
                    $minSizeString = 'origin';
                    foreach ($sizeArray as $sizeItem) {
                        if ($sizeItem !== 'origin' && strpos($sizeItem, 'x') !== false) {
                            if (explode('x', $sizeItem)[0] < $minSize) {
                                $minSizeString = $sizeItem;
                            }
                        }
                    }
                    $thumbUrl = "{$mediaServer['request_url']}/{$path}{$md5Name}_{$minSizeString}.{$ext}";
                } else {
                    $thumbUrl = $mediaData['thumb'];
                }

                break;
        }

        return [
            'size' => $mediaSize,
            'thumb' => $thumbUrl
        ];
    }

    /**
     * 检查模块的缩略图是否存在
     * @param $linkId
     * @param $module
     * @return array
     */
    protected function checkWhetherThumbOfModuleExists($linkId, $module)
    {
        $filter = [
            'link_id' => $linkId,
            'module' => $module,
            'type' => 'thumb'
        ];

        $mediaModel = model(MediaModel::class);
        $userMediaData = $mediaModel->where($filter)->find();

        return !empty($userMediaData) ? $userMediaData : [];
    }

    /**
     * 上传媒体
     * @param $param
     * @return array
     */
    public function upload($param)
    {
        $module = $param['module'] ?? '';
        $linkIdArray = explode(',', $param['link_id']);
        $description = array_key_exists('description', $param) ? $param['description'] : '';
        $resData = [];

        $mediaModel = model(MediaModel::class);

        foreach ($linkIdArray as $linkId) {
            foreach ($param['media_data'] as $media) {
                $tempMedia = $this->getMediaThumb($media, $param['media_server']);

                // 缩略图类型查询是否存在
                $checkThumbExistsMediaData = $this->checkWhetherThumbOfModuleExists($linkId, $param["module"]);

                if (empty($checkThumbExistsMediaData)) {
                    // 不存在新增
                    $addData = [
                        'link_id' => $linkId,
                        'module' => $param["module"],
                        'type' => $param["type"],
                        'size' => $tempMedia['size'],
                        'thumb' => $tempMedia['thumb'],
                        'md5_name' => $media['md5_name'],
                        'description' => $description,
                        'param' => $media
                    ];

                    $resData[] = $mediaModel->addItem($addData);
                } else {
                    // 存在更新当前数据
                    $mediaModel->where(['id' => $checkThumbExistsMediaData['id']])->setField('thumb', $tempMedia['thumb']);

                    $checkThumbExistsMediaData['thumb'] = $tempMedia['thumb'];
                    $resData[] = $checkThumbExistsMediaData;
                }
                //  如果是module user
                if ($module === 'user') {
                    Cache::rm("user_avatar_:" . $linkId);
                }
            }
        }

        return $resData;
    }


    /**
     * 生成处理媒体添加数据
     * @param $data
     * @param $mediaServerParam
     * @return mixed
     * @throws \Exception
     */
    public function generateMediaData(&$data, $mediaServerParam = [])
    {
        $mediaData = $data;

        if (!empty($mediaServerParam)) {
            $mediaServerData = $mediaServerParam;
        } elseif (!empty($data['request_url'])) {
            // 利用media_data里的request_url来重置媒体服务器的request_url
            $mediaServerData['request_url'] = $data['request_url'];
        } else {
            throw new LogicException("missing service request_url field", ErrorCode::MISSING_SERVICE_REQUEST_URL_FIELD);
        }

        $uploadType = $data['upload_type'] ?? 'media_service';
        $mediaSize = '';
        $thumbUrl = '';
        $path = $data['path'] ?? '';
        $md5Name = $data['md5_name'] ?? '';
        $ext = $data['ext'] ?? '';
        $thumb = $data['thumb'] ?? '';
        $width = $data["width"] ?? '';
        $height = $data["height"] ?? '';
        switch ($data["type"]) {
            case 'video':
                // 视频保存原始尺寸
                $mediaSize = "{$width}x{$height}";
                if ($uploadType === 'media_service') {
                    $pathTrim = str_replace('/' . $md5Name . '/', '', $path);
                    $thumbUrl = $mediaServerData['request_url'] . '/' . $pathTrim . $thumb;
                } else {
                    $thumbUrl = $thumb;
                }
                break;
            case 'image':
                if ($uploadType === 'media_service') {
                    // 获取图片上传尺寸
                    $mediaSize = $data["size"] ?? '';
                    $sizeArray = explode(',', $mediaSize);
                    $minSize = 999999;
                    $minSizeString = 'origin';
                    foreach ($sizeArray as $sizeItem) {
                        if ($sizeItem !== 'origin' && strpos($sizeItem, 'x') !== false) {
                            if (explode('x', $sizeItem)[0] < $minSize) {
                                $minSizeString = $sizeItem;
                            }
                        }
                    }
                    $thumbUrl = "{$mediaServerData['request_url']}/{$path}{$md5Name}_{$minSizeString}.{$ext}";
                } else {
                    $thumbUrl = $thumb;
                }
                break;
        }

        if (!array_key_exists("base_url", $mediaData) && isset($mediaServerData['request_url']) && isset($mediaData['path'])) {
            // 缩略图地址
            $mediaData["base_url"] = $mediaServerData['request_url'] . "/" . $mediaData['path'];
        }

        // 缩略图尺寸
        $data["size"] = $mediaSize;

        // 缩略图相对路径
        $data["thumb"] = $thumbUrl;

        // 缩略图参数
        $data["param"] = $mediaData;

        return $data;
    }

    public function find($param)
    {
        $res = model(MediaModel::class)->where($param['param']['filter'])->find();
        if (!empty($res)) {
            $res['param'] = json_decode($res['param'], true);
        }
        return $res;
    }
}
